<template>
	<!-- 我的/设置/修改资料 -->
	<view class="edit-info wrap-card">
		<u-cell-group :border="false">
		    <!-- 头像 -->
		    <u-cell title="头像" size="large" :border="false" :titleStyle="{fontSize:'32rpx',color:'#9CA3AF'}" @click="handleHeader">
		        <image slot="value" class="header-img" :src="form.avatarUrl" mode="aspectFill"></image>
		        <u-icon slot="right-icon" name="edit-pen" size="30" color="#9CA3AF"></u-icon>
		    </u-cell>
		
		    <!-- 昵称 -->
		    <u-cell title="昵称" size="large" :border="false" :titleStyle="{fontSize:'32rpx',color:'#9CA3AF'}" @click="handleName">
		        <view slot="value">{{ form.username }}</view>
		        <u-icon slot="right-icon" name="edit-pen" size="30" color="#9CA3AF"></u-icon>
		    </u-cell>
		
		    <!-- 手机号 -->
		    <u-cell title="手机号" size="large" :border="false" :titleStyle="{fontSize:'32rpx',color:'#9CA3AF'}" @click="handlePhone">
		        <view slot="value">{{ form.phoneNumber }}</view>
		        <u-icon slot="right-icon" name="edit-pen" size="30" color="#9CA3AF"></u-icon>
		    </u-cell>
		
		    <!-- 邮箱 -->
		    <u-cell title="邮箱" size="large" :border="false" :titleStyle="{fontSize:'32rpx',color:'#9CA3AF'}" @click="handleEmail">
		        <view slot="value">{{ form.email }}</view>
		        <u-icon slot="right-icon" name="edit-pen" size="30" color="#9CA3AF"></u-icon>
		    </u-cell>
		
		    <!-- 简介 -->
		    <u-cell title="简介" size="large" :border="false" :titleStyle="{fontSize:'32rpx',color:'#9CA3AF'}" @click="handleIntro">
		        <view slot="value" class="ellipsis-line-1">{{ form.bio }}</view>
		        <u-icon slot="right-icon" name="edit-pen" size="30" color="#9CA3AF"></u-icon>
		    </u-cell>
		</u-cell-group>
		<!-- 手机号 -->
		<uni-popup ref="phoneDialog" type="dialog">
		    <uni-popup-dialog ref="phoneClose" mode="input" title="输入手机号" :value="form.phoneNumber"
		        placeholder="请输入手机号" @confirm="phoneConfirm"></uni-popup-dialog>
		</uni-popup>
		
		<!-- 邮箱 -->
		<uni-popup ref="emailDialog" type="dialog">
		    <uni-popup-dialog ref="emailClose" mode="input" title="输入邮箱" :value="form.email"
		        placeholder="请输入邮箱地址" @confirm="emailConfirm"></uni-popup-dialog>
		</uni-popup>
		
		<!-- 简介 -->
		<uni-popup ref="introDialog" type="dialog">
		    <uni-popup-dialog ref="introClose" mode="textarea" title="个人简介" :value="form.bio"
		        placeholder="介绍一下自己吧" @confirm="introConfirm"></uni-popup-dialog>
		</uni-popup>
		<!-- 底部操作 -->
		<view class="wrap-bottom-bar">
			<view class="bar-placeholder"></view>
			<view class="bar-content">
				<u-button :customStyle="btnStyle" :ripple="true" shape="circle" @click="submit">完成</u-button>
			</view>
		</view>
		<!-- 昵称 -->
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="输入昵称" :value="form.username" placeholder="请输入内容"
				@confirm="nameConfirm"></uni-popup-dialog>
		</uni-popup>
		<!-- 城市选择 -->
		<city-picker themeColor="#007AFF" ref="cityPicker" :pickerValueDefault="cityDefault" @onConfirm="confirmCity">
		</city-picker>
	</view>
</template>

<script>
import { UserApi,CommonApi  } from '../../api';

	export default {
		data() {
			return {
				form: {
				    avatarUrl: '',
				    username: '',
				    phoneNumber: '',     // 示例手机号
				    email: '', // 示例邮箱
				    bio: '' // 简介
				},
				// 按钮配置
				btnStyle: {
					width: "90%",
					height: "75rpx",
					background: "linear-gradient(-45deg,#01906c,#34D399)",
					color: "#FFFFFF",
					fontSize: "30rpx",
				},
			}
		},
		onLoad() {
			this.getUserInfo();
		},
		methods: {
			// 查询个人资料
			async getUserInfo(){
				const res = await UserApi.getMe();
				if(res && res.code === 200) { // 假设成功的响应码是200
				    this.form = {
				        ...this.form,
				        ...res.data, // 假设API返回的数据都在data字段下
				    };
				} else {
				    uni.showToast({ title: '获取用户信息失败', icon: 'none' });
				}
				
			},
			// 修改头像
			async handleHeader() {
			    try {
			        const res = await new Promise((resolve, reject) => {
			            uni.chooseImage({
			                count: 1,
			                success: resolve,
			                fail: reject
			            });
			        });
			
			        const tempFilePath = res.tempFilePaths[0];
			
			        uni.showLoading({ title: '上传中...' });
			
			        // 调用上传接口
			        const uploadRes = await CommonApi.uploadFile(tempFilePath);
			
			        uni.hideLoading();
			
			        if (uploadRes && uploadRes.code === 200) {
			            uni.showToast({ title: '上传成功', icon: 'success' });
			            this.form.avatarUrl = uploadRes.data.url; // 更新头像 URL
			        } else {
			            uni.showToast({ title: '上传失败', icon: 'none' });
			        }
			
			    } catch (e) {
			        uni.hideLoading();
			        console.error("上传头像出错", e);
			        uni.showToast({ title: '上传失败，请重试', icon: 'none' });
			    }
			},
			
			// 修改昵称
			handleName() {
			    this.$refs.inputDialog.open();
			},
			nameConfirm(val) {
			    this.form.username = val;
			},
		
			// 修改手机号
			handlePhone() {
			    this.$refs.phoneDialog.open();
			},
			phoneConfirm(val) {
			    const phoneReg = /^1[3-9]\d{9}$/;
			    if (!phoneReg.test(val)) {
			        uni.showToast({ title: '手机号格式错误', icon: 'none' });
			        return;
			    }
			    this.form.phoneNumber = val;
			},
		
			// 修改邮箱
			handleEmail() {
			    this.$refs.emailDialog.open();
			},
			emailConfirm(val) {
			    const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
			    if (!emailReg.test(val)) {
			        uni.showToast({ title: '邮箱格式错误', icon: 'none' });
			        return;
			    }
			    this.form.email = val;
			},
		
			// 修改简介
			handleIntro() {
			    this.$refs.introDialog.open();
			},
			introConfirm(val) {
			    this.form.bio = val;
			},
		
			// 提交
			async submit() {
			    try {
			        // 调用接口提交数据
			        const res = await UserApi.updateUserInfo(this.form);
			        if (res.code === 200) {
			            uni.showToast({ title: '保存成功', icon: 'success' });
			            setTimeout(() => {
			                uni.navigateBack();
			            }, 1000);
			        } else {
			            uni.showToast({ title: '保存失败', icon: 'none' });
			        }
			    } catch (err) {
			        console.error('保存失败：', err);
			        uni.showToast({ title: '网络错误，请重试', icon: 'none' });
			    }
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit-info {
		.header-img {
			width: 100rpx;
			height: 100rpx;
			border-radius: 100%;
			margin-right: 10rpx;
		}
	}
</style>
